<?php
/**
 * Created by PhpStorm.
 * User: 35482
 * Date: 2021/10/31
 * Time: 17:25
 */

namespace app\pipeline\admin;


use app\admin\controller\Admin;
use app\api\controller\Api;
use app\common\builder\ZBuilder;
use app\company\model\Company as CompanyModel;
use app\pipeline\model\Checklog as ChecklogModel;
use app\pipeline\model\Pipe as PipeModel;
use app\pipeline\model\Business as BusinessModel;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;

class Checklog extends Admin
{
    //检测记录点列表
    public function index($group='tab1'){

        $map=$this->getMap();
        if($this->user_auth['role']!==1&&$this->user_auth['company_id']!==0){
            $map[]=['company_id','=',$this->user_auth['company_id']];
        }
        $business_id=$this->request->param('id');
        if($business_id){
            $map[]=['business_id','=',$business_id];
        }
        $page_triger=true;//分页开关
        //筛选参数过滤
        $company_id=[];
        foreach($map as $key=>$val){
            $vals=explode('.',$val[0]);
            if($val[0]=='company_id'){
                $company_id=$val[2];
            }
            if($vals[0]!='c'){
                $val[0]='c.'.$val[0];
                $map[$key]=$val;
            }
            if($val[0]=='c.pipeline_number'&&!empty($val[2])){
                $page_triger=false;
            }
        }

        //设置筛选参数
        $business_info=BusinessModel::field('pipeline_company,pipeline_number')->where('id',$business_id)->find();
        $company_filter=CompanyModel::whereIn('id',$business_info['pipeline_company'])->column('name','id');
        $pipeline_filter=PipeModel::whereIn('company_id',$company_id)->column('number','id');

        //根据管道编号查询时不分页,避免影响拖拽排序
        if(!$page_triger){
            $data_list = ChecklogModel::alias('c')
                ->field('c.*,c.company_id as p_company_id,c.pipeline_number as checkpipe_number,o.name as company_id,p.number as pipeline_number')
                ->where($map)
                ->leftJoin('company o','o.id = c.company_id')
                ->leftJoin('pipeline p','p.id = c.pipeline_number')
                ->order('c.pipeline_number,c.sort desc','desc')->select()->toArray();
        }else{
            $data_list = ChecklogModel::alias('c')
                ->field('c.*,c.company_id as p_company_id,c.pipeline_number as checkpipe_number,o.name as company_id,p.number as pipeline_number')
                ->where($map)
                ->leftJoin('company o','o.id = c.company_id')
                ->leftJoin('pipeline p','p.id = c.pipeline_number')
                ->order('c.pipeline_number,c.sort desc','desc')->paginate();
        }

        $list_tab = [
            'tab1' => ['title' => '数据列表', 'url' => url('index',['group'=>'tab1','id'=>$business_id])],
            'tab2' => ['title' => '地图展示', 'url' => url('checklog_map',['group'=>'tab2','id'=>$business_id])],
        ];
        //拖拽单元样式
        $extra_css="
                    <style>
                    .dd-dragel { position: absolute; pointer-events: none; z-index: 9999; background:#FF8905}
                    </style>
                    ";
        $sort_reset=[
            'title' => '重置序号',
            'icon'  => 'fa fa-fw fa-refresh',
            'class' => 'sort_reset btn btn-default page-reload'
        ];
        return ZBuilder::make('table')
            ->setPageTitle('检测记录') // 页面标题
            ->setTableName('checklog') // 设置表名
            ->setSearch(['p.name' => '管道编号','c.sort'=>'点位']) // 设置搜索参数
            ->setTabNav($list_tab,$group)
            ->addTopSelect('company_id','管道所属公司',$company_filter,'','pipeline_number')
            ->addTopSelect('pipeline_number','管道编号',$pipeline_filter)
            ->hideCheckbox()
            ->addColumn('check','变更序号','',"<button class='drags fa fa-arrows  btn-default'></button>",'','dd-handle')
            ->addColumns([ // 批量添加列
                ['id', 'ID','','','','point_id'],
                ['company_id', '管道所属公司'],
                ['p_company_id','管道所属公司id'],
                ['pipeline_number', '管道编号','','','','point_pipe'],
                ['sort', '点位序号','','','','point_sort'],
                ['longtitude', '经度'],
                ['latitude', '纬度'],
                ['deep', '埋深'],
                ['thickness', '测点厚度'],
                ['create_time', '记录时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('custom',$sort_reset)
            ->addRightButton('edit',['title'=>'编辑','href' => url('checklog_save', ['id' => '__id__'])],true)
            ->addRightButton('delete',['title'=>'删除','href' => url('checklog_del', ['id' => '__id__']),'data-title' => '删除后将重新排序,确定删除？'])
            ->setRowList($data_list) // 设置表格数据
            ->js('libs/jquery-nestable/jquery.nestable')
            ->js('checklog_sort')
            ->setExtraCss($extra_css)
            ->fetch(); // 渲染模板
    }
    //拖拽排序修改
    public function drag_sort_save(){
        if($this->request->isAjax()){
            $post_data=$this->request->post();
            if(!empty($post_data['sort_id'])){
                $ids=array_column($post_data['sort_id'],'id');
                $new_sort=[];
                $ori_sort=1;
                for($i=count($ids)-1;$i>=0;$i--){
                    $row=[];
                    $row['id']=$ids[$i];
                    $row['sort']=$ori_sort;
                    $row['update_time']=date('Y-m-d H:i:s');
                    $new_sort[]=$row;
                    $ori_sort++;
                }
                $chelogmodel=new ChecklogModel();
                $res=$chelogmodel->saveAll($new_sort,true);
                if(!$res){
                    return json_encode(['msg'=>'修改排序失败','code'=>false],JSON_UNESCAPED_UNICODE);
                }
                return json_encode(['msg'=>'修改排序成功','code'=>true],JSON_UNESCAPED_UNICODE);

            }
            return false;
        }
        return false;
    }
    //检测记录点保存
    public function checklog_save(){
        $id=$this->request->param('id');
        $info=ChecklogModel::get($id);
        // 显示编辑页面
        return ZBuilder::make('form')
            ->setPageTitle('编辑检测记录点信息')
            ->setPageTips('请谨慎操作','warning')
            ->addStatic('pipeline_number', '管道编号')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'longtitude', '经度'],
                ['text', 'latitude', '纬度'],
                ['text', 'thickness', '壁厚'],
                ['text','sort','点位顺序'],
                ['text', 'deep', '埋深'],
                ['text','type','设备型号'],
                ['text','accuracy','设备精确度'],
                ['text','other','设备参数等(待补充)']
            ])
            ->setFormData($info)
            ->fetch();
    }
    //检测记录点删除
    public function checklog_del(){
        $id=$this->request->param('id');
        $row_data=ChecklogModel::where("id",$id)->find();
        Db::startTrans();
        try{
            $res=ChecklogModel::where("id",$id)->delete();
            if(!$res){
                Db::rollback();
                $this->error('删除失败');
            }
            //删除检测点后重新排序
            $where=[];
            $where['business_id']=$row_data['business_id'];
            $where['company_id']=$row_data['company_id'];
            $where['pipeline_number']=$row_data['pipeline_number'];
            $ori_sort=$row_data['sort'];
            $ids=ChecklogModel::where($where)->where('sort','>',$row_data['sort'])->order('sort asc')->column('id');
            $new_sort=[];
            for($i=0;$i<=count($ids)-1;$i++){
                $row=[];
                $row['id']=$ids[$i];
                $row['sort']=$ori_sort;
                $row['update_time']=date('Y-m-d H:i:s');
                $new_sort[]=$row;
                $ori_sort++;
            }
            if(!empty($new_sort)){
                $chelogmodel=new ChecklogModel();
                $res=$chelogmodel->saveAll($new_sort,true);
                if(!$res){
                    Db::rollback();
                    $this->error('删除排序失败');
                }
                Db::commit();
                $this->success('删除成功');
            }
        }catch(Exception $e){
            Db::rollback();
            $this->error('删除失败');
        }

    }
    //检测记录点地图显示
    public function checklog_map($group='tab2'){
        $business_id=$this->request->param('id');
        $list_tab = [
            'tab1' => ['title' => '数据列表', 'url' => url('index',['group'=>'tab1','id'=>$business_id])],
            'tab2' => ['title' => '地图展示', 'url' => url('checklog_map',['group'=>'tab2','id'=>$business_id])],
        ];

        $business_info=BusinessModel::field('pipeline_company,pipeline_number')->where('id',$business_id)->find();
        $company_list=CompanyModel::field('id,name')->whereIn('id',$business_info['pipeline_company'])->select();
        $tab_nav=[
            'tab_list' => $list_tab,
            'curr_tab' => $group
        ];
        $this->assign('business_id',$business_id);
        $this->assign('page_tips','检测记录');
        $this->assign('tab_nav',$tab_nav);
        $this->assign('company_list',$company_list);
        return $this->fetch();
//        return ZBuilder::make('table')
//            ->setPageTitle('检测记录') // 页面标题
//            ->setTableName('checklog') // 设置表名
//            ->setTabNav($list_tab,$group)
//            ->addFilter()
//            ->setExtraJs('<script type="javascript">console.debug(123213)</script>')
//            ->setTemplate('checklog_map')
//            ->fetch();
    }

    /**
     * 前端页面ajax获取检测点和管道数据
     */
    public function ajax_get_pipeinfo(){
        if($this->request->isAjax()){
            $post_data=$this->request->post();
            if(!empty($post_data['type'])){
                if(empty($post_data['business_id'])){
                    json_return('缺少业务ID',false);
                }
                $where=[];
                $where['business_id']=$post_data['business_id'];
                $new_data=[];
                switch($post_data['type']){
                    case 'all':
                        break;
                    case 'company':
                        if(empty($post_data['company_id'])){
                            json_return('缺少公司ID',false);
                        }
                        $new_data['pipeline_info']=PipeModel::field('id,name,number')->where('company_id',$post_data['company_id'])->select()->toArray();
                        $where['company_id']=$post_data['company_id'];
                        break;
                    case 'pipeline':
                        if(empty($post_data['pipeline_number'])){
                            json_return('缺少公司ID',false);
                        }
                        $where['pipeline_number']=$post_data['pipeline_number'];
                }

                $all_sort=ChecklogModel::field('company_id,pipeline_number,sort,longtitude,latitude')
                    ->where($where)
                    ->order('sort asc')
                    ->select()->toArray();
                if(!$all_sort){
                    json_return('获取检测点失败',false);
                }
                $pipeline_numbers=array_unique(array_column($all_sort,'pipeline_number'));
                $new_data['sort_info']=[];
                foreach($pipeline_numbers as $key=>$val){
                    $row_data=[];
                    foreach($all_sort as $v){
                        if($val==$v['pipeline_number']){
                            $new_data['sort_info'][$key]['company_id']=$v['company_id'];
                            $new_data['sort_info'][$key]['pipeline_number']=(int)$v['pipeline_number'];
                            unset($v['pipeline_number']);
                            unset($v['company_id']);
                            $row_data[]=$v;
                        }
                    }
                    $new_data['sort_info'][$key]['data']=$row_data;
                }
                json_return('获取检测点成功',true,$new_data);
            }
        }
        json_return('参数错误');
    }


}